<?php

namespace app\api\controller;

use app\api\service\TimePlanService;
use think\Controller;
use think\Db;

class Dingshijihua extends Controller
{  //服务器定时任务
    public function _empty($name)
    {
        die('非法访问！你的IP已被监控！');
    }

    /**
     * @name 开盘价格
     * @author zay
     * @Date 2020/3/26 0026 09:28
     */

    public function openprice()
    {
        $setting = setting();
        $current_price = $setting['current_price'];
        $res = true;
        $jiaoyi_price = $current_price;
        if (date('H') == 0) {
            $rand = mt_rand($setting['increase_min'], $setting['increase_max']);
            $new_price = number_format($current_price + $rand * 0.01, 2);
            $res = db('setting')->where('key', 'current_price')->update(['val' => $new_price]);
            if($res){
                $jiaoyi_price = $new_price;
            }
        }
        if ($res) {
            //把为确认的求购单价格自动变掉
            $list = Db('ppdd')->where(['zt' => 0, 'is_del' => 0])->select();
            foreach ($list as $k => $v) {
                $total_money = bcmul($v['num'], $jiaoyi_price, 2);
                db('ppdd')->where(['id' => $v['id']])->update(['price' => $jiaoyi_price, 'total_money' => $total_money, 'update_time' => time()]);
            }
            echo "更新成功";
        } else {
            echo "更新失败";
        }

    }

    /**
     * @name 全球分红脚本
     * @author zay
     * @Date 2020/3/23 0023 14:18
     */

    public function globaldividend()
    {
        //获取佣金设置
        $union_reward = setting('union_reward');
        $union_reward = json_decode($union_reward, true);
        $union_reward = $union_reward ? $union_reward : [];
        if (empty($union_reward)) {
            echo "工会未设置";
            exit;
        }
        //获取工会等级的会员
        $list = DB('user')->field('id,uname,tj_num,level')->where('tj_num', '>', $union_reward[0]['num'])->select();
        foreach ($list as $k => &$v) {
            $active_count = $this->teamactive($v['id']);
            $team_power = $this->teampower($v['id']);
            //团队会员数量
            $team_member_list = $this->teammember($v['id']);
            //团队交易量
            $team_jiaoyi_num = $this->teamjiaoyi($v['id']);
            //矿机类型 1-体验矿， 2-微矿， 3-小矿， 4-中矿， 5-大矿， 6-超矿
            $type = 0;
            $rate = 0;
            $rank = 0; // 工会等级
            $level_reward = isset($union_reward[$v['level']]) ? $union_reward[$v['level']] : [];
            if (empty($level_reward)) {
                echo "奖励未设置";
                exit;
            }
            //查询该用户直推多少人
            $zt_num = Db('user')->field('count(*) as count')->where(['is_effect' => 1, 'tid' => $v['id']])->find();
            $zt_num = !empty($zt_num['count']) ? $zt_num['count'] : 0;
            $v['tj_num'] = $zt_num;
            switch ($v['level']) {
                case 0:
                    //一级工会：直接推荐20人，团队活跃500人，工会算力达到500G，送小矿机1台，享受当天交易佣金15%的全球分红
                    if ($v['tj_num'] >= $level_reward['num'] && $active_count >= $level_reward['active'] & $team_power >= $level_reward['power']) {
                        $type = $level_reward['kj_id'];
                        $rate = $level_reward['rate'];
                        $rank = 1;
                    }
                    break;
                case 1://升级为二级
                    //二级工会：直接推荐40人，团队活跃2000人，工会算力达到3000G，送中型云矿机1台，享受当天交易佣金20%的全球分红
                    if ($v['tj_num'] >= $level_reward['num'] && $active_count >= $level_reward['active'] & $team_power >= $level_reward['power']) {
                        $type = $level_reward['kj_id'];
                        $rate = $level_reward['rate'];
                        $rank = 2;
                    }
                    break;
                case 2://升级为三级
                    //三级工会：直接推荐80人，三个一级会员，团队活跃8000人工会算力达到20000G，送大型云矿机1台，享受交易佣金15%的全球分红
                    if ($v['tj_num'] >= $level_reward['num'] && $active_count >= $level_reward['active'] & $team_power >= $level_reward['power'] && isset($team_member_list[1]) && $team_member_list[1] >= $level_reward['member']) {
                        $type = $level_reward['kj_id'];
                        $rate = $level_reward['rate'];
                        $rank = 3;
                    }
                    break;
                case 3://升级为四级
                    //四级工会：直接推荐160人，3个二级会员，团队活跃5万人数，工会算力达到100000G，送超矿机1台，享受交易佣金10%的全球分红
                    if ($v['tj_num'] >= $level_reward['num'] && $active_count >= $level_reward['active'] & $team_power >= $level_reward['power'] && isset($team_member_list[2]) && $team_member_list[2] >= $level_reward['member']) {
                        $type = $level_reward['kj_id'];
                        $rate = $level_reward['rate'];
                        $rank = 4;
                    }
                    break;
                case 4://升级为五级级
                    //五级工会:直推320人，3个三级会员，团队活跃15万人，团队算力达到35万G,享受当天交易佣金5%的全球分红
                    if ($v['tj_num'] >= $level_reward['num'] && $active_count >= $level_reward['active'] & $team_power >= $level_reward['power'] && isset($team_member_list[3]) && $team_member_list[3] >= $level_reward['member']) {
                        $type = $level_reward['kj_id'];
                        $rate = $level_reward['rate'];
                        $rank = 5;
                    }
                    break;
                default:
                    break;
            }
            if (empty($type) || empty($rate)) {
                continue;
            }
            DB::startTrans();
            try {
                //会员赠送矿机
                if ($type) {
                    //获取矿机信息
                    $kj_list = DB('shop_project')->column('name,price,imagepath,yxzq,kjsl,capacity', 'id');
                    $insert_data = [
                        'mobile' => $v['uname'],
                        'project' => $kj_list[$type]['name'],
                        'addtime' => time(),
                        'zt' => 0,
                        'imagepath' => $kj_list[$type]['imagepath'],
                        'yxzq' => $kj_list[$type]['yxzq'],
                        'price' => $kj_list[$type]['price'],
                        'kjsl' => $kj_list[$type]['kjsl'],
                        'kjbh' => orderSn(),
                        'uid' => $v['id'],
                        'capacity' => $kj_list[$type]['capacity'],
                        'type' => 3,
                        'kj_type' => $type
                    ];
                    //var_dump($insert_data);exit;
                    //查询用户是否已经送过
                    $kj_info = DB('shop_orderform')->where(['type' => 3, 'kj_type' => $type, 'uid' => $v['id']])->find();
                    if (empty($kj_info)) {
                        $res = Db('shop_orderform')->insert($insert_data);
                        if (!$res) {
                            throw new \Exception('赠送矿机失败');
                        }
                    }
                }
                $reward = number_format($team_jiaoyi_num * $rate / 100, 2);
                //会员佣金分红
                if ($rate && $reward) {
                    $userinfo = userinfobyid($v['id']);
                    $reward = number_format($team_jiaoyi_num * $rate / 100, 2);
                    $res = DB('user')->where(['id' => $v['id']])->update(['idc' => $userinfo['idc'] + $reward, 'update_time' => time()]);
                    if (!$res) {
                        throw new \Exception('账户金币变更失败');
                    }
                    //添加金币记录
                    $log_insert = [
                        'uid' => $v['id'],
                        'uname' => $v['uname'],
                        'type' => 4,
                        'mqian' => $userinfo['idc'],
                        'money' => $reward,
                        'mhou' => $userinfo['idc'] + $reward,
                        'note' => '全球分红',
                        'time' => time(),
                    ];
                    $res1 = DB('logocoin')->insert($log_insert);
                    if (!$res1) {
                        throw new \Exception('金币记录添加失败');
                    }
                }
                //加入工会
                //检查用户是否加入工会
                $gong_info = Db('shequ')->where(['uid' => $v['uid']])->find();
                $gong_insert = [
                    'uid' => $v['id'],
                    'uname' => $v['uname'],
                    'ctime' => time(),
                    'etime' => time(),
                    'zt' => 1,
                ];
                $last_insert_id = 0;
                if (empty($gong_info)) {
                    $last_insert_id = Db('shequ')->insertGetId($gong_insert);
                    if (!$last_insert_id) {
                        throw new \Exception('加入工会失败');
                    }
                }
                $param = ['level' => $rank, 'update_time' => time()];
                if ($last_insert_id) {
                    $param['issq'] = $last_insert_id;
                }
                //更新会员等级
                $res = db('user')->where(['id' => $v['id']])->update($param);
                if (!$res) {
                    throw new \Exception('更新失败');
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                echo "msg" . $e->getMessage();
            }

        }
        echo "工会奖励发放成功";
    }

    /**
     * @name 统计团队活跃
     * @author zay
     * @Date 2020/3/23 0023 14:25
     * @return string
     */

    protected function teamactive($uid)
    {
        $ids_sx = Db('user')->where("FIND_IN_SET({$uid},tpath)")->column('id');
        $count = Db('user')->field('count(id) as count')->where("FIND_IN_SET({$uid},tpath)")
            ->where('sessionid', 'neq', '')->find();
        $count = !empty($count['count']) ? $count['count'] : 0;
        return $count;
    }

    /**
     * @name 计算工会算力
     * @author zay
     * @Date 2020/3/26 0026 14:14
     * @param $uid
     * @return array|false|int|mixed|\PDOStatement|string|\think\Model
     */

    protected function teampower($uid)
    {
        $ids_sx = Db('user')->where("FIND_IN_SET({$uid},tpath)")->column('id');
        $count = Db('user')->field('sum(power) as power')->where("FIND_IN_SET({$uid},tpath)")
            ->where(['is_effect' => 1])->find();
        $count = !empty($count['power']) ? $count['power'] : 0;
        return $count;
    }

    /**
     * @name 计算团队会员
     * @author zay
     * @Date 2020/3/26 0026 14:14
     * @param $uid
     * @return array|false|int|mixed|\PDOStatement|string|\think\Model
     */

    protected function teammember($uid)
    {
        $list = Db('user')->field('level,count(*) as count')->where("FIND_IN_SET({$uid},tpath)")
            ->where(['is_effect' => 1])->where('level', '>', 0)->group('level')->select();
        if ($list) {
            $list = array_column($list, null, 'level');
        }
        return $list;
    }

    /**
     * @name 计算团队当天交易量
     * @author zay
     * @Date 2020/3/26 0026 14:14
     * @param $uid
     * @return array|false|int|mixed|\PDOStatement|string|\think\Model
     */

    protected function teamjiaoyi($uid)
    {
        $ids_sx = Db('user')->where("FIND_IN_SET({$uid},tpath)")->column('id');
        $total_num = Db('ppdd_jiaoyi')->field('sum(num) as num')
            ->whereIn('sell_id', $ids_sx)
            ->whereTime('confirm_time', 'today')
            ->where(['zt' => 2])
            ->find();
        $total_num = !empty($total_num['num']) ? $total_num['num'] : 0;
        return $total_num;
    }

    /**
     * @name 日K线数据
     * @author zay
     * @Date 2020/3/23 0023 15:21
     */

    public function kday()
    {
        $last_day = date('Y-m-d', strtotime('-1 day'));
        //查询昨天收盘的价格
        $last_k_day = DB('k_day')->where(['date' => $last_day])->find();
        if (empty($last_k_day)) {
            $open_price = setting('current_price');
        } else {
            $open_price = $last_k_day['stop_price'];
        }
        //获取当天最高、最低价格
        $jiaoyi_day = DB('ppdd_jiaoyi')->field('max(price) as max_price,min(price) as min_price,sum(num) as num')
            ->whereTime('time', 'today')->find();
        $num = 0;
        $max_price = $open_price;
        $min_price = $open_price;
        if ($jiaoyi_day && $jiaoyi_day['max_price'] && $jiaoyi_day['min_price'] && $jiaoyi_day['num']) {
            $max_price = $jiaoyi_day['max_price'];
            $min_price = $jiaoyi_day['min_price'];
            $num = $jiaoyi_day['num'];
        }
        //获取最后的交易价
        $last_jiayi = DB('ppdd_jiaoyi')->field('price')
            ->whereTime('time', 'today')
            ->order('time desc')
            ->limit(1)->find();
        //查询当天数据是否存在 存在更新 不存在添加
        $k_day = Db('k_day')->where(['date' => date('Y-m-d')])->find();
        $data = [
            'max_price' => (string)$max_price,
            'min_price' => (string)$min_price,
            'num' => (string)$num,
            'open_price' => $open_price,
            'stop_price' => $last_jiayi ? $last_jiayi['price'] : $open_price,
            'update_time' => time(),
        ];
        if (empty($k_day)) {
            $data['date'] = date('Y-m-d');
            Db('k_day')->insert($data);
        } else {
            DB('k_day')->where(['id' => $k_day['id']])->update($data);
        }
    }

    /**
     * @name 分享奖励
     * @author zay
     * @Date 2020/3/25 0025 16:31
     */

    public function fenxiang()
    {
        TimePlanService::service()->fenxiang();
    }

    /**
     * @name 邀请奖励币每天释放
     * @author zay
     * @Date 2020/3/25 0025 16:31
     */

    public function release_coin()
    {
        TimePlanService::service()->release_coin();
    }

    /**
     * @name 超时未付款取消订单
     * @author zay
     * @Date 2020/3/31 0031 12:08
     */

    public function order_cancel()
    {
        TimePlanService::service()->order_cancel();
    }

    /**
     * @name 超时未放币交易自动完成
     * @author zay
     * @Date 2020/3/31 0031 12:08
     */

    public function order_complete()
    {
        TimePlanService::service()->order_complete();
    }
}
